package com.zzyl.service.impl;

import com.zzyl.dto.LoginDto;
import com.zzyl.mapper.UserMapper;
import com.zzyl.service.LoginService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.security.crypto.password.PasswordEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description LoginServiceImpl
 * @Author Hua Caoxing
 * @Data 2025-08-31
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserVo login(LoginDto loginDto) {
        //根据用户名查询用户信息
        //管理员密码 888itcast.CN764%...
        UserVo userVo = userMapper.selectOne(loginDto.getUsername());
        if(userVo == null){
          throw new RuntimeException("用户名不存在");
        }
        //密码校验
        boolean matches = passwordEncoder.matches(loginDto.getPassword(), userVo.getPassword());
        if(!matches){
            throw new RuntimeException("密码错误");
        }

        Map<String,Object> map = new HashMap<>();
        map.put("username",loginDto.getUsername());

        // 创建token，并设置到userVo
        userVo.setUserToken(JwtUtil.createJWT("itheima",600000,map));
        return userVo;
    }
}
